<template>
  <div class="config_container">
    <div class="setting_btn" v-if="btnShow">
      <span class="el-icon-setting setting_ico" @click="handleOpen"></span>
    </div>
    <el-dialog
      title="配置选项"
      v-if="isShowSettingDialog"
      :visible.sync="dialogVisible"
      top="50px"
      width="86%"
      append-to-body
      :close-on-click-modal="true"
      :before-close="handleClose"
      class="config_setting_dialog"
    >
      <div class="config_wrap" v-loading="loading">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础配置" name="baseconfig">
            <BaceConfigForm v-if="dialogVisible" ref="BaceConfigForm"/>
          </el-tab-pane>
          <el-tab-pane label="HIS申请列表配置" name="hisapplytable">
            <TableConfigForm v-if="dialogVisible" ref="TableConfigForm"/>
          </el-tab-pane>
          <el-tab-pane label="预约记录列表配置" name="appointmentListForm">
            <appointmentListForm v-if="dialogVisible" ref="appointmentListForm" :from="'applyHis'" :dialog-visible-parent="dialogVisible"/>
          </el-tab-pane>
          <el-tab-pane label="临床预约配置" name="clinicalAppointment">
            <ClinicalAppointmentConfigForm v-if="dialogVisible" ref="ClinicalAppointmentConfigForm"/>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
        <el-button size="small" type="primary" @click="settingSend">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Options } from '@/utils/constant'
import { getparamtersettings } from '@/api/api'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
import { isArrObjectEqual, isNull, setIsHaveAppConfig, getIsHaveAppConfig } from '@/utils/utils'
import BaceConfigForm from './baseConfigForm'
import TableConfigForm from './tableConfigForm'
import AppointmentListForm from './appointmentList'
import ClinicalAppointmentConfigForm from './clinicalAppointmentConfigForm'
export default {
  components: {
    BaceConfigForm,
    AppointmentListForm,
    ClinicalAppointmentConfigForm,
    TableConfigForm
  },
  props: {
    btnShow: {
      type: Boolean,
      default: true
    },
    configVisible: {
      type: Boolean,
      default: false
    },
    hospitalCode: {
      type: String,
      default: ''
    },
    configType: {
      // user 为个人配置
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isShowSettingDialog: false,
      loading: false,
      // dialogVisible: false,
      activeName: 'baseconfig',
      configInfo: {
        baseConfig: {},
        checkHisTable: [],
        checkPatTypeTable: [],
        checkHisTableColumnsConfig: []
      },
      isAlreadyHavePatType: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.configVisible
      },
      set(val) {
        this.$emit('update:configVisible', val)
      }
    },
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    isCloseAutoRefreshOnSaveAppConfig() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isCloseAutoRefreshOnSaveAppConfig
    }
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val) {
          this.getAppConfig()
        }
      },
      immediate: true
    }
  },
  created() {
    // console.log('created=>checkRegistrationConfig')
  },
  beforeDestroy() {
    console.log('beforeDestroy=>checkRegistrationConfig')
  },
  methods: {
    initConfig() {
      const _checkHisTable = {
        columnsConfig: this.configInfo.checkHisTableColumnsConfig,
        checkHisTable: this.configInfo.checkHisTable,
        checkPatTypeTable: this.configInfo.checkPatTypeTable
      }
      // console.log('_checkHisTable === ', _checkHisTable)
      this.$refs.TableConfigForm && this.$refs.TableConfigForm.setData(_checkHisTable)
      this.$refs.BaceConfigForm && this.$refs.BaceConfigForm.setData(this.configInfo.baseConfig)
    },
    getAppConfig() {
      console.log('getAppConfig')
      this.loading = true
      const userId = this.$store.state.user.id
      const params = {
        hospitalCode: this.hospitalCode,
        userId: userId
      }
      getparamtersettings(params).then(res => {
        if (res && res.code === 10000) {
          let configInfo = null
          if (res.content.hospitalParameterContent) {
            configInfo = res.content.hospitalParameterContent
            // window.configInfo1 = JSON.parse(res.content.hospitalParameterContent)
          }
          if (res.content.userParameterContent && this.configType === 'user') {
            configInfo = res.content.userParameterContent
          }
          if (configInfo) {
            const _info = JSON.parse(configInfo)
            console.warn('_info', _info)
            this.configInfo.baseConfig = _info.baseConfig || {}
            this.configInfo.checkHisTable = (_info.checkHisTable && _info.checkHisTable.length) ? _info.checkHisTable : Options.emergencyOptions
            this.configInfo.checkPatTypeTable = (_info.checkPatTypeTable && _info.checkPatTypeTable.length) ? _info.checkPatTypeTable : Options.patientTypeItemOptions
            this.configInfo.checkHisTableColumnsConfig = (_info.checkHisTableColumnsConfig && _info.checkHisTableColumnsConfig.length) ? _info.checkHisTableColumnsConfig : Options.checkTableColumnsConfig
            const _checkHisTable = {
              checkHisTable: this.configInfo.checkHisTable,
              checkPatTypeTable: this.configInfo.checkPatTypeTable,
              columnsConfig: this.configInfo.checkHisTableColumnsConfig
            }
            console.log('_checkHisTable===', _checkHisTable)
            this.$refs.BaceConfigForm && this.$refs.BaceConfigForm.setData(this.configInfo.baseConfig)
            this.$refs.TableConfigForm && this.$refs.TableConfigForm.setData(_checkHisTable)
            // 判断数据库中是否有配置了参数的标签设置, 用来判断处理保存配置参数的时候，参数数据偶尔会丢失的问题
            let isHaveAppConfig = {
              baseConfig: false,
              emergencyTable: false,
              patientTypeTable: false,
              hisColumnsTable: false
            }
            if (!isNull(_info.baseConfig)) {
              isHaveAppConfig.baseConfig = true
            }
            if (!isNull(_info.checkHisTable)) {
              isHaveAppConfig.emergencyTable = true
            }
            if (!isNull(_info.checkPatTypeTable)) {
              isHaveAppConfig.patientTypeTable = true
            }
            if (!isNull(_info.checkHisTableColumnsConfig)) {
              isHaveAppConfig.hisColumnsTable = true
            }
            setIsHaveAppConfig(isHaveAppConfig)
          }
        } else {
          this.dialogVisible = false
        }
      }).finally(() => {
        setTimeout(() => {
          this.loading = false
        }, 1000)
      })
    },
    handleOpen() {
      this.isShowSettingDialog = true
      this.$nextTick(() => {
        this.dialogVisible = true
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.isShowSettingDialog = false
    },
    handleClick() {},
    // 配置保存
    async settingSend() {
      let baseConfig = await this.$refs.BaceConfigForm.getData()
      console.log('baseConfig==>==', baseConfig)
      let checkHisTable = await this.$refs.TableConfigForm.getData()
      console.log('checkHisTable==>==', checkHisTable)
      const apponitmentList = await this.$refs.appointmentListForm.tabledataColumnsConfig
      console.log('apponitmentList', apponitmentList)
      let appConfig = this.configInfo
      const clinicalAppointmentConfig = await this.$refs.ClinicalAppointmentConfigForm.getData() // 临床预约
      console.log('clinicalAppointmentConfig', clinicalAppointmentConfig)
      appConfig.baseConfig = baseConfig
      appConfig.checkHisTable = checkHisTable.checkHisTable // 急诊标志
      appConfig.checkPatTypeTable = checkHisTable.checkPatTypeTable // 患者类型
      appConfig.checkHisTableColumnsConfig = checkHisTable.columnsConfig // his申请单header配置
      appConfig.bookTable = apponitmentList // 已预约列表header配置
      // 判断HIS列表prop字段是否被重复设置的问题
      let hisTableCount = {}
      appConfig.checkHisTableColumnsConfig.forEach(item => {
        if (hisTableCount[item.prop]) {
          hisTableCount[item.prop] += 1
        } else {
          hisTableCount[item.prop] = 1
        }
      })
      console.log('hisTableCount', hisTableCount)
      let isHisTableColumnsRepetition = false
      const hisTableKeys = Object.keys(hisTableCount)
      hisTableKeys.forEach(key => {
        if (hisTableCount[key] > 1) {
          isHisTableColumnsRepetition = true
          this.$alert(`HIS申请单列表数据配置中${key}字段重复，请仔细检查并删除重复项后再保存。`, '系统提示', {
            confirmButtonText: '确定',
            callback: action => {
              // this.$message({
              //   type: 'info',
              //   message: `action: ${ action }`
              // });
            }
          })
          return
        }
      })
      if (this.isAlreadyHavePatType || appConfig.checkPatTypeTable.filter(item => item.name === '').length > 0) {
        // console.error('appConfig.checkPatTypeTable', appConfig.checkPatTypeTable)
        this.$alert('患者类型存在重复的或有空值', '系统提示', {
          confirmButtonText: '确定',
          callback: action => {
            // this.$message({
            //   type: 'info',
            //   message: `action: ${ action }`
            // });
          }
        })
        return
      }
      if (isHisTableColumnsRepetition) return
      // 判断配置参数是否全部为constant.js中初始化的参数
      let isEqualDefaultConfig = {
        // baseConfig: false,
        emergencyTable: false,
        patientTypeTable: false,
        hisColumnsTable: false
      }
      let isSetAppConfig = getIsHaveAppConfig()
      if (isSetAppConfig.emergencyTable) {
        let emArr = []
        Options.emergencyOptions.forEach((item) => {
          item.name = item.label
          delete item.label
          emArr.push(item)
        })
        if (isArrObjectEqual(appConfig.checkHisTable, emArr)) {
          isEqualDefaultConfig.emergencyTable = true
        }
      }
      if (isSetAppConfig.patientTypeTable) {
        let patTypeArr = []
        Options.patientTypeItemOptions.forEach((item) => {
          item.name = item.label
          delete item.label
          patTypeArr.push(item)
        })
        if (isArrObjectEqual(appConfig.checkPatTypeTable, patTypeArr)) {
          isEqualDefaultConfig.patientTypeTable = true
        }
      }
      if (isSetAppConfig.hisColumnsTable) {
        if (isArrObjectEqual(appConfig.checkHisTableColumnsConfig, Options.checkTableColumnsConfig)) {
          isEqualDefaultConfig.hisColumnsTable = true
        }
        // if (JSON.stringify(appConfig.checkHisTableColumnsConfig) === JSON.stringify(Options.checkTableColumnsConfig)) {
        //   isEqualDefaultConfig.hisColumnsTable = true
        // }
      }
      console.log('isEqualDefaultConfig', isEqualDefaultConfig)
      if (isEqualDefaultConfig.emergencyTable && isEqualDefaultConfig.patientTypeTable && isEqualDefaultConfig.hisColumnsTable) {
        // this.$message.success('当前配置为系统默认配置')
        this.$confirm('当前HIS申请单列表配置为系统默认配置，若存在之前的配置数据丢失的问题，请找技术人员检查，当前数据若保存将会还原到系统默认配置，是否确定要保存？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.saveConfigData(appConfig, clinicalAppointmentConfig)
        }).catch(() => {
          // 取消
          setTimeout(() => {
            if (this.isCloseAutoRefreshOnSaveAppConfig == false) {
              window.location.reload()
            }
          }, 1000)
        })
      } else {
        this.saveConfigData(appConfig, clinicalAppointmentConfig)
      }
    },
    saveConfigData(appConfig, clinicalAppointmentConfig) {
      console.log('saveConfigData=>clinicalAppointmentConfig', clinicalAppointmentConfig)
      // appConfig.baseConfig = baseConfig
      // appConfig.checkHisTable = checkHisTable.checkHisTable // 急诊标志
      // appConfig.checkPatTypeTable = checkHisTable.checkPatTypeTable // 患者类型
      // appConfig.checkHisTableColumnsConfig = checkHisTable.columnsConfig // his申请单header配置
      // appConfig.bookTable = apponitmentList // 已预约列表header配置
      this.loading = true
      // { value: 1, label: '门诊', bgColor: '', fontColor: '', colorStatus: false, sort: 1 },
      // 过滤掉暂时用不到的字段，节省参数存储空间，因为数据库中字段的存储字符串长度有限
      appConfig.checkPatTypeTable.forEach(item => {
        if (!item.colorStatus) {
          delete item.bgColor
          delete item.fontColor
          delete item.colorStatus
          delete item.sort
        }
      })
      // { value: 0, label: '普通', bgColor: '', fontColor: '', colorStatus: false, sort: 1 },
      appConfig.checkHisTable.forEach(item => {
        if (!item.colorStatus) {
          delete item.bgColor
          delete item.fontColor
          delete item.colorStatus
          delete item.sort
        }
      })
      // { label: '患者', width: '90', prop: 'patientName', show: true, sort: 1 },
      appConfig.checkHisTableColumnsConfig.forEach(item => {
        delete item.sort
      })
      // delete appConfig.baseConfig
      // delete appConfig.checkHisTable
      // delete appConfig.checkPatTypeTable
      // delete appConfig.checkHisTableColumnsConfig
      const params = {
        hospitalCode: this.hospitalCode,
        parameterContent: JSON.stringify(appConfig),
        clinicalContent: JSON.stringify(clinicalAppointmentConfig)
      }
      this.$store.dispatch('settings/setConfigSetting_hospital', params).then((res) => {
        if (res && res.code === 10000) {
          this.$message.success(res.message || '设置医院配置参数成功！')
          this.dialogVisible = false
          this.isAlreadyHavePatType = false
          if (this.hospitalCode === this.$store.state.user.hospitalCode) {
            this.$store.dispatch('settings/getAppConfigSetting')
          }
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
        setTimeout(() => {
          if (this.isCloseAutoRefreshOnSaveAppConfig == false) {
            window.location.reload()
          }
        }, 1500)
      })
      // 对院区和影像区域的配置更新后，对本地缓存数据进行更新
      const checkFormDefault = getLocalStorage('CHECK_FORM_DEFAULT')
      // 用于配置检查预约下拉菜单之后更新本地存储的areaName和depArea的值
      if (checkFormDefault) {
        let cfd = JSON.parse(checkFormDefault)
        cfd.depArea = appConfig.baseConfig.depArea ? cfd.depArea : ''
        cfd.areaName = appConfig.baseConfig.areaName ? cfd.areaName : ''
        setLocalStorage('CHECK_FORM_DEFAULT', JSON.stringify(cfd))
      }
    },
    alreadyHavePatType(val) {
      this.isAlreadyHavePatType = val
    }
  }
}
</script>

<style lang="scss" scoped>
.config_container{
  // overflow: hidden;
  // overflow-y: scroll;
  // display: inline-block;
  .setting_btn{
    padding: 2px;
    color: #666;
    font-size: 20px;
    cursor: pointer;
    &:hover{
      color: #00C0EF
    }
  }
}
.config_setting_dialog{
  overflow: hidden;
  /deep/ .el-dialog__body{
    padding: 5px 20px;
    max-height: calc(100vh - 220px);
    overflow: hidden;
  }
}
</style>
